<script setup lang="ts">
import { onMounted, nextTick, onActivated } from 'vue';

defineOptions({
    name: 'Advertisement'
})

interface Props {
    adType: 'adx' | 'adsense',
    path?: string,
    id: number | string,
    size?: Array<number | string>,
    isGrid?: boolean,
    row?: number | string
}

const props = withDefaults(defineProps<Props>(), {
    adType: 'adx',
    path: '',
    id: '',
    size: () => [300, 250],
    isGrid: false,
    row: 0
})

const style = {
    '--row': props.row
}

let slot: any = null
function handleLoadAdScript() {
    window.googletag = window.googletag || { cmd: [] };
    window.googletag.cmd.push(function () {
        slot = window.googletag.defineSlot(props.path, props.size, props.id).addService(window.googletag.pubads());
        // googletag.pubads().enableSingleRequest();
        window.googletag.pubads().collapseEmptyDivs();
        window.googletag.enableServices();
    });
}

function handleRefershAd() {
    if (slot) {
        window.googletag.pubads().refresh([slot]);
    }
}

onMounted(() => {
    if (props.adType === 'adx') {
        handleLoadAdScript()
        nextTick(() => {
            window.googletag.cmd.push(function () { window.googletag.display(props.id); });
        })
    }

    if (props.adType === 'adsense') {
        nextTick(() => {
            (window.adsbygoogle = window.adsbygoogle || []).push({});
        })
    }
})

onActivated(() => {
    nextTick(() => {
        if (props.adType === 'adx') {
            handleRefershAd()
        }
    })
})
</script>

<template>
    <div class="ad" :class="{ grid: isGrid }" :style="style">
        <div class="ad-wrapper">
            <div v-if="props.adType === 'adx'" :id="(props.id as string)" :style="{ minWidth: `${props.size[0]}px`, minHeight: `${props.size[1]}px` }">
            </div>
            <ins v-if="props.adType === 'adsense'" class="adsbygoogle"
                :style="{ display: 'inline-block', minWidth: `${props.size[0]}px`, minHeight: `${props.size[1]}px` }"
                data-ad-client="ca-pub-5489637365884864" :data-ad-slot="props.id"></ins>
        </div>
    </div>
</template>

<style scoped lang="scss">
.ad {
    width: 100%;
    text-align: center;
    font-size: var(--s-fontsize);
    margin: 0 auto;
    color: #ffffff;

    &-wrapper {
        width: 100%;
        margin: 0 auto;

        &>div {
            display: flex;
            justify-content: center;
        }
    }

    &.grid {
        --column-count: 2;
        grid-area: var(--row) / 1 / 1 span/ var(--column-count) span;

        @media screen and (min-width: 768px) {
            --column-count: 4;
        }

        @media screen and (min-width: 1024px) {
            --column-count: 5;
        }

        @media screen and (min-width: 1367px) {
            --column-count: 6;
        }
    }
}
</style>